package com.handu.luna.core.domain.promotion;

import com.handu.luna.core.domain.user.User;
import com.handu.luna.core.domain.user.UserRank;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

import javax.persistence.Entity;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * Created by wangzailiang on 2014/7/2 .
 */
@Entity
public class RedPacket extends Bonus {



    /**
     * 通过红包类型ID查询所有红包(分页)
     * @param redPacketPromotionId
     * @param pageable
     * @return
     */
    public Page<RedPacket> findAllByRedPacketPromotionId(Long redPacketPromotionId,Pageable pageable) {
        Page<RedPacket> page = context.getRedPacketRepository().findAllByBonusPromotionId(redPacketPromotionId, pageable);
        List<RedPacket> list = page.getContent();
        for(RedPacket redPacket : list) {
            redPacket.init();
        }
        return page;
    }

    /**
     * 通过红包类型ID查询所有红包
     * @param redPacketPromotionId
     * @return
     */
    public List<RedPacket> findAllByRedPacketPromotionId(Long redPacketPromotionId) {
        List<RedPacket> list = context.getRedPacketRepository().findAllByBonusPromotionId(redPacketPromotionId);
        for(RedPacket redPacket : list) {
            redPacket.init();
        }
        return list;
    }

    /**
     * 红包Excel导出
     * @param redPacketPromotionId
     * @return
     */
    public HSSFWorkbook getExcelModel(Long redPacketPromotionId) {

        List<RedPacket> redPacketList = new RedPacket().findAllByRedPacketPromotionId(redPacketPromotionId);

        HSSFWorkbook wb = new HSSFWorkbook();
        int sheetCount = redPacketList.size()/60000 + 1;
        int beginIndex = 0;
        int endIndex = sheetCount > 1 ? 60000 : redPacketList.size();

        for (int sheetNum = 1; sheetNum <= sheetCount; sheetNum++) {

            HSSFSheet sheet = wb.createSheet("红包"+(sheetCount > 1 ? sheetNum :""));
            Row headerRow = sheet.createRow(0);
            headerRow.createCell(0).setCellValue("红包序列号");
            headerRow.createCell(1).setCellValue("红包金额");
            headerRow.createCell(2).setCellValue("类型名称");
            headerRow.createCell(3).setCellValue("使用结束日期");

            for(int i=beginIndex,j=0; i<endIndex; i++,j++) {
                RedPacket redPacket = redPacketList.get(i);

                Row row = sheet.createRow(j+1);
                row.createCell(0).setCellValue(redPacket.getCode());
                row.createCell(1).setCellValue(redPacket.getBonusPromotion().getBonusPrice().toString());
                row.createCell(2).setCellValue(redPacket.getBonusPromotion().getName());
                String strDate = "";
                if(redPacket.getBonusPromotion().getUseEndDate() != null) {
                    strDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(redPacket.getBonusPromotion().getUseEndDate());
                }
                row.createCell(3).setCellValue(strDate);
            }

            beginIndex = 60000 * sheetNum;
            endIndex = sheetCount > (sheetNum+1) ? 60000*(sheetNum + 1) : redPacketList.size();
        }

        return wb;

    }

    public void delete(Long id,Long redPacketPromotionId) {
        RedPacket redPacket = context.getRedPacketRepository().findOne(id);
        RedPacketPromotion redPacketPromotion = context.getRedPacketPromotionRepository().findOne(redPacketPromotionId);
        redPacketPromotion.updateGrantNum(redPacketPromotionId, -1L);
        if(StringUtils.isNotBlank(redPacket.getOrderId())) {
            redPacketPromotion.updateUsedNum(redPacketPromotionId,-1L);
        }
        context.getRedPacketRepository().delete(id);
    }

    /**
     * 生成序列号
     */
    public void generateCode() {
        StringBuilder code = new StringBuilder(String.valueOf(bonusPromotionId));
        code.append(System.nanoTime());
        setCode(code.toString());
    }

    /**
     * 初始化红包类型数据
     */
    public void init() {
        this.setBonusPromotion(context.getRedPacketPromotionRepository().findOne(bonusPromotionId));
        if(userId != null) {
            this.setUser(context.getUserRepository().findOne(userId));
        }
    }

    public RedPacket save(RedPacket redPacket) {
        redPacket.generateCode();
        context.getRedPacketRepository().save(redPacket);
        return redPacket;
    }


    public String getSucessFlashMessage(String message){
        String messagePrefix = (null==this.getId() ?"添加" : "修改");
        return messagePrefix + message + "成功";
    }

    public RedPacket() {

    }

    public RedPacket(String code, Long userId, String orderId, Date usedDate, Long bonusPromotionId) {
        super(code,userId,orderId,usedDate);
        this.bonusPromotionId = bonusPromotionId;
    }


    /**
     * 根据类型ID 和发放数量 发放
     * @param redPacketPromotionId
     * @param grantNum
     */
    public void save(Long redPacketPromotionId, Long grantNum) {

        for(int i=0; i<grantNum; i++) {
            RedPacket redPacket = new RedPacket();
            redPacket.setBonusPromotionId(redPacketPromotionId);
            this.save(redPacket);
        }

        new RedPacketPromotion().updateGrantNum(redPacketPromotionId, grantNum);
    }

    public Long saveByUserRankId(Long userRankId,Long redPacketPromotionId) {

        UserRank userRank = context.getUserRankRepository().findOne(userRankId);
        List<User> userList = context.getUserRepository().findbyLevelPoint((int)userRank.getMinRank(),(int)userRank.getMaxRank());

        long grantNum = 0L;

        for(User user : userList) {
            RedPacket redPacket = new RedPacket();
            redPacket.generateCode();
            redPacket.setBonusPromotionId(redPacketPromotionId);
            redPacket.setUserId(user.getId());
            this.save(redPacket);
            grantNum++;
        }

        new RedPacketPromotion().updateGrantNum(redPacketPromotionId, grantNum);

        return grantNum;
    }

    public Long saveByUsersId(List<Long> userIds, Long redPacketPromotionId) {

        long grantNum = 0L;

        for(Long id: userIds) {
            RedPacket redPacket = new RedPacket();
            redPacket.generateCode();
            redPacket.setBonusPromotionId(redPacketPromotionId);
            redPacket.setUserId(id);
            this.save(redPacket);
            grantNum++;
        }

        new RedPacketPromotion().updateGrantNum(redPacketPromotionId, grantNum);

        return grantNum;
    }
}
